//
//  CountDownButton.swift
//  CustomViews
//
//  Created by PMC on 2019/8/7.
//  Copyright © 2019 unitTao. All rights reserved.
//

import UIKit

typealias ECCountDownHandler = (_ finished: Bool) -> Void

class CountDownButton: UIButton {
    
    private let title = "s后重试"
    
    var completion: ECCountDownHandler?
    
    var timer: Timer?
    
    var isTimer: Bool = false
    
    var duration: Int = 0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setTitle("发送验证码", for: .normal)
        setTitleColor(.mainColor, for: .normal)
        setTitleColor(.mainColorGray, for: .disabled)
        titleLabel?.font = .regular(16)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setTitle("发送验证码", for: .normal)
        setTitleColor(.main, for: .normal)
        setTitleColor(.mainGray, for: .disabled)
        titleLabel?.font = .regular(16)
    }
    
    func countDown(with duration: Int, completion: ECCountDownHandler? = nil) {
        isEnabled = false
        isTimer = true
        self.duration = duration
        self.completion = completion
        
        setTitle(String(format: "%ld%@", duration, title), for: .disabled)
        startTimer()
    }
    
    func reset() {
        invalidTimer()
        isEnabled = true
        isTimer = false
    }
    
    private func startTimer() {
        let timer = Timer.scheduledTimer(timeInterval: 1,
                                         target: self,
                                         selector: #selector(count),
                                         userInfo: nil,
                                         repeats: true)
        self.timer = timer
        RunLoop.main.add(timer, forMode: .common)
    }
    
    private func invalidTimer() {
        timer?.invalidate()
        timer = nil
    }
    
    @objc private func count() {
        duration -= 1
        if duration == 0 {
            isTimer = false
            invalidTimer()
            isEnabled = true
            if completion != nil {
                completion!(true)
            }
        } else {
            setTitle(String(format: "%ld%@", duration, title), for: .disabled)
        }
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        if newSuperview == nil {
            invalidTimer()
        }
    }
}
